﻿using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace Test.MVC
{
    public class PlainTextTypeFormatter : MediaTypeFormatter//MediaTypeFormatter是用于使用 ObjectContent 处理序列化和反序列化强类型对象的基类。
    {

        public PlainTextTypeFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
        }

        public override bool CanReadType(Type type)
        {
            return false;
        }

        public override bool CanWriteType(Type type)
        {
            return type == typeof(string);
        }

        public override async Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            using (var sw = new StreamWriter(writeStream))
            {
                await sw.WriteAsync(value.ToString());
            }
        }
    }
}